// import glob from 'glob'
import config from '../config'
import Router from 'koa-router'
import requireDir from 'require-dir'

const admin = requireDir('./admin')
const client = requireDir('./client')
const article = requireDir('./article')
const comment = requireDir('./comment')
const qiniu = requireDir('./qiniu')
const tag = requireDir('./tag')
const sort = requireDir('./sort')
const about = requireDir('./about')

const router = new Router({
  prefix: config.baseApi
})

const routesLoader = function () {
  return new Promise((resolve, reject) => {
    const obj = {...admin, ...client, ...article, ...comment, ...qiniu, ...tag, ...sort, ...about}
    const routers = []
    Object.keys(obj).forEach(name => {
      routers.push(obj[name]['default'](router))
    })
    resolve(routers)
  })
}

export default function (app) {
  routesLoader().then(routes => {
    routes.forEach(route => {
      app
        .use(router.routes())
        .use(router.allowedMethods())
    })
  })
}

// const router = new Router({
//   prefix: config.baseApi
// })
// // router.prefix(config.baseApi)
// const routesLoader = function (dirname) {
//   return new Promise((resolve, reject) => {
//     const routers = []
//     glob(
//       `${dirname}/*`,
//       {ignore: '**/index.js'},
//       (err, files) => {
//         if (err) {
//           reject(err)
//         }
//         files.forEach(file => {
//           const route = require(file)
//           routers.push(route['default'](router))
//         })
//         resolve(routers)
//       }
//     )
//   })
// }
//
// export default function (app) {
//   routesLoader(`${__dirname}`).then(routes => {
//     routes.forEach(route => {
//       app
//         .use(router.routes())
//         .use(router.allowedMethods())
//     })
//   })
// }
